const fs = require('fs');
const axios = require('axios');
const util = require('util');
const folderPath = 'C:\\Users\\57693\\Desktop\\test'
const chokidar = require('chokidar');

const username = 'admin';
const password = '123456';
let path2IdMap = new Map()
const baseUrl = 'http://localhost:8042'
const instanceUrl = `${baseUrl}/instances`
const readFileAsync = util.promisify(fs.readFile);

const watcher = chokidar.watch(folderPath, {
    persistent: true,
});

watcher
    .on('add', (path) => {
        upload(path)
    })
    .on('change', (path) => console.log(`File ${path} has been changed`))
    .on('unlink', (path) => {
        console.log(`File ${path} has been removed`)
        deleteInstance(path)
    });

const upload = async (path1) => {
    const dicomData = await readFileAsync(path1)
    axios({
        method: 'post',
        url: instanceUrl,
        data: dicomData,
        auth: {
            username: username,
            password: password
        },
        headers: {
            'Content-Type': 'application/dicom',
        }
    })
        .then(response => {
            save2Map(path1, response.data)
        })
        .catch(error => {
            console.error('DICOM文件上传失败:', error);
        });
}

const save2Map = (filePath, data) => {
    if (data.ID) {
        path2IdMap.set(filePath, data.ID)
    }
}


const deleteInstance = (filePath) => {
    const instanceId = path2IdMap.get(filePath)
    if (!instanceId) {
        return
    }
    console.log(`删除instanceId:${instanceId}`)
    axios({
        method: 'delete',
        url: `${instanceUrl}/${instanceId}`,
        auth: {
            username: username,
            password: password
        }
    })
        .then(response => {
            console.log(`Instance ${instanceId} has been successfully deleted`);
        })
        .catch(error => {
            console.error('Error deleting instance:', error.response.data);
        });
}
